<?php
/**
 * Created by PhpStorm.
 * User: huynguyen
 * Date: 9/27/14
 * Time: 9:32 AM
 */

namespace Library\Upload;

use Phalcon\Image\Adapter\GD;
use Phalcon\Image\Adapter\Imagick;
use Common\Models\Images\Images;
use Common\Models\Images\ImageLink;
use Library\Upload\Ftp;

class UploadFile extends \Phalcon\Mvc\User\Component
{
    public function __construct()
    {

    }

    public function loadLibraryScript()
    {
        $this->assets
            ->addCss('vendor/jquery-file-upload/css/jquery.fileupload.css')
            ->addCss('vendor/jquery-file-upload/css/jquery.fileupload-ui.css')
            ->addCss('vendor/bootstrap-tagsinput/dist/bootstrap-tagsinput.css')

            ->addJs('vendor/jquery-file-upload/js/vendor/jquery.ui.widget.js')
            //->addJs('http://blueimp.github.io/JavaScript-Load-Image/js/load-image.all.min.js')
            //->addJs('http://blueimp.github.io/JavaScript-Canvas-to-Blob/js/canvas-to-blob.min.js')
            ->addJs('vendor/jquery-file-upload/js/jquery.iframe-transport.js')
            ->addJs('vendor/jquery-file-upload/js/jquery.fileupload.js')
            ->addJs('vendor/jquery-file-upload/js/jquery.fileupload-process.js')
            ->addJs('vendor/jquery-file-upload/js/jquery.fileupload-image.js')
            ->addJs('vendor/jquery-file-upload/js/main.js');
    }

    public function doUpload($data , $listThumbnail)
    {
        //Print the real file names and their sizes
        foreach ($this->request->getUploadedFiles() as $file){
            $fileName = strtotime("now") . $file->getName();
            $imagePath = $data['folder_upload'] . '/' . $fileName;
            if($file->moveTo($imagePath))
            {
                switch(strtolower($file->getType()))
                {
                    case 'image/png':
                    case 'image/jpg':
                    case 'image/jpeg':
                    case 'image/gif':
                        if($listThumbnail != null)
                        {
                            foreach($listThumbnail as $key => $thumbnail)
                            {
                                $dirPathThumbnail = $data['folder_upload'] . '/thumbnail/' . $key . '/';
                                if (!file_exists($dirPathThumbnail) && !is_dir($dirPathThumbnail)) {
                                    mkdir($dirPathThumbnail , 0777);
                                }

                                $imagePathThumbnail = $dirPathThumbnail . $fileName;
                                $imageUpload = new GD($imagePath);
                                $imageUpload->resize($thumbnail['width'] , $thumbnail['height']);
                                $upload = $imageUpload->save($imagePathThumbnail , 100);
                            }
                        }
                        break;
                }

                $images = new Images();
                $images->assign(array(
                    'image_path'    => $fileName ,
                    'width'         => 0,
                    'height'        => 0,
                    'size'          => $file->getSize()
                ));
                $images->save();

                if($data['type'] == 'M')
                {
                    if($data['object_type'] == 'video' || $data['object_type'] == 'video_group')
                    {
                        if($file->getKey() == 'file_poster')
                        {
                            $data['type'] = 'C';
                        }
                    }

                    $imageLink = ImageLink::find(array(
                        "object_id = " . $data['object_id'] . " AND object_type = '" .$data['object_type'] ."' AND type = '" . $data['type'] . "'"
                    ))->getFirst();
                }
                else{
                    $imageLink = null;
                }

                if($imageLink && is_object($imageLink) && $imageLink->getId() > 0)
                {
                    $imagesDelete = Images::find(array(
                        "id = " . $imageLink->getImageId()
                    ))->getFirst();
                    if($imagesDelete)
                    {
                        $imagesDelete->delete();
                        unlink($data['folder_upload'] . '/' . $imagesDelete->getImagePath());
                    }

                    $imageLink->setImageId($images->getId());
                    $imageLink->setDetailedId($images->getId());

                    if(!$imageLink->update())
                    {
                        die(print_r($imageLink->getMessages()));
                    }
                }
                else
                {
                    $imageLink = new ImageLink();
                    $imageLink->assign(array(
                        'object_id'     => $data['object_id'] ? $data['object_id'] : 0,
                        'object_type'   => $data['object_type'] ? $data['object_type'] : '',
                        'image_id'      => $images->getId(),
                        'detailed_id'   => $images->getId(),
                        'type'          => $data['type'],
                        'position'      => $data['position']
                    ));
                    if(!$imageLink->save())
                    {
                        die(print_r($imageLink->getMessages()));
                    }
                }

            }
        }
    }

    public function doUploadFtp($data , $listThumbnail)
    {
        try {
            $ftp = new Ftp;
            $ftp->connect($this->config->fpt->server);
            $ftp->login($this->config->fpt->user, $this->config->fpt->pass);

            foreach ($this->request->getUploadedFiles() as $file) {
                $fileName = strtotime("now") . $file->getName();
                $data['folder_upload'] = 'advertise';
                $imagePath = $data['folder_upload'] . '/' . $fileName;
                $upload = $ftp->put($imagePath , $file->getPathname() , FTP_BINARY);
                if (!$upload) { echo 'FTP upload failed!'; }
            }

            $ftp->close();
        } catch (\Exception $e) {
            echo 'Error: ', $e->getMessage();
        }
    }
} 